import copy
import random
import sys
import time

import pyautogui


def go(main_list):
    max_list = []
    max_score = 0

    for j in range(1, 3000):
        k = kindergarten()
        k.main_list = copy.deepcopy(main_list)
        for i in range(30):
            k.going()

        print("\r", end="")
        print("max:"+str(max_score)+"--doing {}%: ".format(int(j/30)), "▋" * (int(j/30) // 2), end="")
        sys.stdout.flush()

        if max_score == 0:
            max_score = k.score
        else:
            if k.score > max_score:
                max_list = k.step_list
                max_score = k.score

    print("\r")
    print('begin...')
    time.sleep(2)
    for a in max_list:
        dragTo(a[0], a[1], a[2], a[3])


def dragTo(x, y, x1, y1):
    if x == 0 or y == 0 or x1 == 0 or y1 == 0:
        return
    pyautogui.moveTo(x, y)
    pyautogui.dragTo(x1, y1)
    time.sleep(0.1)


class kindergarten:
    def __init__(self):
        self.main_list = []
        self.score = 0
        self.step_list = []

    def going(self):
        for x in range(len(self.main_list)):
            for y in range(len(self.main_list[x])):
                self.match(x, y)

    def match(self, x, y):
        item = self.main_list[x][y]
        item["dx"] = x
        item["dy"] = y
        if item["no"] == 0:
            return

        dx = 0
        while dx < 10 - x:
            dy = 0
            while dy <= 15 - y:
                x1 = x + dx
                y1 = y + dy

                to_match_list = self.get_to_match(x, y, x1, y1)

                t_sum = self.matchSum(to_match_list)

                if t_sum > 10:
                    dy += 1
                    break
                if t_sum == 10:
                    self.finish(to_match_list)
                    dy += 1
                    break
                dy += 1
            dx += 1

    def get_to_match(self, x, y, x1, y1):
        l_list = []
        dx = x
        while dx <= x1:
            dy = y
            while dy <= y1:
                item = self.main_list[dx][dy]
                item["dx"] = dx
                item["dy"] = dy
                l_list.append(item)
                dy += 1
            dx += 1

        return l_list

    def matchSum(self, to_list):
        sum = 0
        for i in to_list:
            sum += i["no"]

        return sum

    def finish(self, to_list):
        rand_n = random.randint(0, 1)
        if rand_n == 0:
            return

        begin = end = {}
        for i in to_list:
            end = i
            if not begin:
                begin = i

            if i["no"] > 0:
                self.score += 1
        for i in to_list:
            self.main_list[i["dx"]][i["dy"]] = {"no": 0, "x": i['x'], "y": i['y']}

        self.step_list.append([begin['x'], begin['y'], end['x'], end['y']])
